import * as step from '@flow-step/step-toolkit'
import process from 'process'
import {upload} from './ossUpload'
import { exec } from 'child_process';
import {installOssutil} from './install'

async function runStep(): Promise<void> {

    try {
        await step.exec.call('ossutil', ['--version'],{
            listener: {
                stdoutLine: (line: string) => step.info(line)
            }
        })
        step.info('found installed ossutil')
    } catch (e) {
        if (process.platform == 'win32') {
            step.error('Please install ossutil or ensure it is in your PATH. Reference: https://help.aliyun.com/zh/oss/developer-reference/install-ossutil')
            throw new Error(`check ossutil failed! ${e}`)
        }
        try {
            await installOssutil('v1.7.19')
        } catch (err) {
            throw new Error(`failed to install ossutil but ${err}`)
        }
    }

    step.info('PIPELINE_ID=' + Number(process.env.PIPELINE_ID));
    step.info('PIPELINE_NAME=' + process.env.PIPELINE_NAME as string);
    step.info('BUILD_NUMBER=' + Number(process.env.BUILD_NUMBER));
    step.info('EMPLOYEE_ID=' + process.env.operator);
    step.info('WORK_SPACE=' + process.env.WORK_SPACE as string);
    step.info('PROJECT_DIR=' + process.env.PROJECT_DIR as string);
    step.info('BUILD_JOB_ID=' + Number(process.env.BUILD_JOB_ID));
    step.info('METAS='+ process.env.METAS);

    await upload();
}

runStep()
    .then(function () {
        step.success('run step OSSUpload successfully!')
    })
    .catch(function (err: Error) {
        step.error(err.message)
        process.exit(-1)
    })
